<script type="text/javascript" charset="UTF-8" src="/redist/npm/clipboard/dist/clipboard.js"></script>
<script type="text/javascript">
  (function () {

    var clipboard = null;
    var rMin = /\.min\.js$/;

    {{#isScriptViewSourcePage}}
    var regenerateId = '#regenerate';
    {{/isScriptViewSourcePage}}

    var allowedIds = [
      '#copyright-raw',
      '#downloadurl-raw',
      '#groupid-raw',
      '#groupid-urn',
      '#license-raw',
      '#require-min',
      '#require-raw',
      '#scriptid-raw',
      '#scriptid-urn',
      '#updateurl-raw',
      '#userid-raw',
      '#userid-urn'
    ];

    function unsupported() {
      allowedIds.forEach(function (aElement, aIndex, aArray) {
        $(aElement).prop('disabled', true);
      });
    }

    {{#isScriptViewSourcePage}}
    // TODO: Should keep in sync with all peg.js upmixes eventually
    function parseMeta(aString) {
      aString = aString.toString();
      var re = /\/\/ @(\S+)(?:\s+(.*))?/;
      var headers = {};
      var name = null;
      var prefix = null;
      var header = null;
      var key = null;
      var value = null;
      var lines = aString.split(/[\r\n]+/).filter(function (aE, aI, aA) {
        return (aE.match(re));
      });
      var line = null;

      for (line in lines) {
        [, name, value] = lines[line].replace(/\s+$/, "").match(re);
        switch (name) {
          case "licence":
            name = "license";
            break;
        }
        [key, prefix] = name.split(/:/).reverse();
        if (key) {
          if (prefix) {
            if (!headers[prefix])
              headers[prefix] = new Object;
            header = headers[prefix];
          }
          else
            header = headers;

          if (header[key]) {
            if (!(header[key] instanceof Array))
              header[key] = new Array(header[key]);
            header[key].push(value || "");
          }
          else
            header[key] = value || "";
        }
      }
      if (headers["license"])
        headers["licence"] = headers["license"];

      return (JSON.stringify(headers) != "{}") ? headers : undefined;
    }

    // NOTE: Keep in sync with helpers.js
    cleanFilename = function (aFilename, aDefaultName) {
      // Blacklist problem characters (slashes, colons, etc.).
      var cleanName = (aFilename || '').replace(/[\\\/:*?\'\"<>|#;@=&]/g, '')

      // Make whitespace readable.
      .replace(/(\s|%20)+/g, '_');

      return cleanName || aDefaultName;
    };
    {{/isScriptViewSourcePage}}

    //
    if (ClipboardJS.isSupported()) {
      clipboard = new ClipboardJS(allowedIds.join(', '));

      clipboard.on('success', function(aE) {
        if (rMin.test(aE.text)) {
          // TODO: Flash tooltip saying copied and then restore it
        } else {
          // TODO: Flash tooltip saying copied and then restore it
        }
      });

      clipboard.on('error', unsupported);

    } else {
      unsupported();
    }

    {{#isScriptViewSourcePage}}
    editor = ace.edit("editor");

    $(regenerateId).on('click', function () {
      var rawSource = editor.getSession().getValue();
      var parser = 'UserScript';
      var block = null;
      var rHeaderContent = new RegExp(
        '^(?:\\uFEFF)?\/\/ ==' + parser + '==([\\s\\S]*?)^\/\/ ==\/'+ parser + '==', 'm'
      );

      var username = '{{authedUser.name}}';
      var names = null;
      var name = null;
      var tryURL = null;
      var updateURL = null;
      var downloadURL = [];
      var activeIdx = 0; // Default if new
      var origin = window.location.origin;

      var headerContent = rHeaderContent.exec(rawSource);
      if (headerContent) {
        block = parseMeta(headerContent);

        if (block['name']) {
          names = block['name'].reverse();
          name = cleanFilename(names[0]);
          if (name) {
            try {
              tryURL = new URL('../' + name, origin);

              if (decodeURIComponent(tryURL.toString()) !== origin + '/' + name) {
                name = encodeURIComponent(name);
              }
            } catch (aE) {
              name = encodeURIComponent(name);
            }

            updateURL = origin + '/meta/' + username + '/' + name + '.meta.js';

            downloadURL.push(origin + '/install/' + username + '/' + name + '.user.js');
            downloadURL.push(origin + '/install/' + username + '/' + name + '.min.user.js');
            downloadURL.push(origin + '/src/scripts/' + username + '/' + name + '.user.js');
            downloadURL.push(origin + '/src/scripts/' + username + '/' + name + '.min.user.js');

            // Find current active
            $('#install-targets li').each(function (aIdx) {
              if ($(this).hasClass('active')) {
                activeIdx = aIdx;
              }
            });

            if( $('#install-targets li').length === 0) {
              // Add DOM html
              $('#install-targets')
                .append('<li class="active"><a href="#" title="">Normal</a></li>');
              $('#install-targets')
                .append('<li><a href="#" title="">Minified</a></li>');
              $('#install-targets')
                .append('<li><a href="#" title="">Normal with counter skip</a></li>');
              $('#install-targets')
                .append('<li><a href="#" title="">Minified with counter skip</a></li>');

              // Add event listeners for new scripts
              $('#install-targets li').each(function (aIdx) {
                $(this).on('click', function (aEv) {
                  // NOTE: Keep in sync with selectIntall.html onClick
                  var containerNode = $(aEv.target).closest('li');

                  $('#downloadurl').val(aEv.target.title);
                  $('#downloadurl-raw').attr(
                    'data-clipboard-text', '// @downloadURL ' + aEv.target.title
                  );

                  // Clear all actives
                  $('#install-targets li').each(function (aIdx) {
                    $(this).removeClass('active');
                  });

                  // Set this active
                  containerNode.addClass('active');
                })
              });
            }

            // Modify title attributes
            $('#install-targets li a').each(function (aIdx) {
              $(this).attr('title', downloadURL[aIdx]);
            });

            // Simulate trigger click (actual doesn't appear to coexist well with *bootstrap*)
            $('#updateurl').val(updateURL);
            $('#updateurl-raw').attr('data-clipboard-text', '// @updateURL ' + updateURL);

            $('#downloadurl').val(downloadURL[activeIdx]);
            $('#downloadurl-raw').attr(
              'data-clipboard-text', '// @downloadURL ' + downloadURL[activeIdx]);

            // Always enable the button here
            $('#alt-install-target-btn').removeAttr('disabled');

            return;
          }
        }
      }

      // Default
        /* Leave existing li element(s) available for future mod */

      $('#updateurl').val('');
      $('#updateurl-raw').attr('data-clipboard-text', '// @updateURL ');
      $('#downloadurl').val('');
      $('#downloadurl-raw').attr('data-clipboard-text', '// @downloadURL ');

      $('#alt-install-target-btn').attr('disabled', 'disabled');
    });
    {{/isScriptViewSourcePage}}

  })();
</script>
